<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="puerylist.query"
            clearable
            @clear="getuserlist"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getuserlist"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="userslist" border stripe>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column label="用户名称" prop="username"> </el-table-column>
        <el-table-column label="手机号" prop="mobile"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="角色" prop="role_name"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="zhuantai(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              plain
              size="mini"
              icon="el-icon-edit"
              @click="xiugai(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              plain
              size="mini"
              icon="el-icon-delete"
              @click="open(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                plain
                size="mini"
                icon="el-icon-setting"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
<!-- 分页器 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="puerylist.pagenum"
          :page-sizes="[1, 2, 3, 4, 5, 10]"
          :page-size="puerylist.pagesize"
          layout="sizes, prev, pager, next"
          :total="total"
        >
        </el-pagination>
      </div>

      <!-- 添加用户的对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <!-- 内容主体区域 -->
        <el-form
          label-width="80px"
          :model="addtian"
          :rules="addFormRules"
          ref="addFormRef"
        >
          <el-form-item label="用户名：" prop="username">
            <el-input v-model="addtian.username"></el-input>
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input v-model="addtian.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱：" prop="email">
            <el-input v-model="addtian.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号：" prop="mobile">
            <el-input v-model="addtian.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户的对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editdialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
     <el-form :model="editForm" :rules="editFormrules" ref="editFormref" label-width="80px">
       <el-form-item label="用户名称">
         <el-input v-model="editForm.username" disabled></el-input>
       </el-form-item>
       <el-form-item label="邮箱">
         <el-input v-model="editForm.email"></el-input>
       </el-form-item>
       <el-form-item label="手机号">
         <el-input v-model="editForm.mobile"></el-input>
       </el-form-item>
     </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editFormadd"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 分配的对话框 -->
      <el-dialog
  title="分配角色"
  :visible.sync="setRoledialogVisible"
  width="50%"
  @close="setRoleDialogClosed"
  >
  <div>
    <p>当前的用户：{{userinfo.username}}</p>
    <p>当前的角色：{{userinfo.role_name}}</p>
     <el-select v-model="selectedRoleid" placeholder="请选择">
    <el-option
      v-for="item in roleslist"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoledialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleinfo">确 定</el-button>
  </span>
</el-dialog>

    </el-card>
  </div>
</template>

<script>
import uri from "../../config/uri";
export default {
  data() {
    // 验证邮箱规则
    var checkEmail = (rule, value, cd) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        // 合法邮箱
        return cd();
      }
      cd(new Error("请出入合法的邮箱"));
    };
    var checkMobile = (rule, value, cd) => {
      // 验证手机号的正则表达式
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cd();
      }
      cd(new Error("请输入合法的手机号"));
    };

    return {
      userslist: [],
      // 获取用户列表的参数
      puerylist: {
        query: "",
        pagenum: 1,
        pagesize: 3,
      },
      //总数据条数
      total: 0,
      // 是否显示添加对话框
      addDialogVisible: false,
      // 是否显示修改对话框
      editdialogVisible: false,
      // 添加用户信息参数
      addtian: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //添加用户的验证规则
      addFormRules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 用户id获取用户信息的参数
      editForm: [],
      // 修改用户的校验规则
      editFormrules:{
        email:[
         { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile:[
           { required: true, message: '请输入用户手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ]
      },
      // 分配角色的对话框是否显示
      setRoledialogVisible:false,
      // 需要被分配角色的用户信息
      userinfo:{},
      // 分配角色，获取角色列表的数据
      roleslist:[],
      // 分配角色，已选中的角色id值
      selectedRoleid:""
    };
  },
  created() {
    this.getuserlist();
  },
  methods: {
    // 获取用户列表
    getuserlist() {
      this.$http
        .get(uri.getusers, {
          params: this.puerylist,
        })
        .then((res) => {
          console.log(res);
          if (res.meta.status === 200) {
            this.userslist = res.data.users;
            this.total = res.data.total;
          }
        });
    },
    // 修改状态
    zhuantai(userinfo) {
      console.log(userinfo);
      this.$http
        .put(uri.putusers + "/" + userinfo.id + "/state/" + userinfo.mg_state)
        .then((res) => {
          console.log(res);
          if (res.meta.status === 200) {
            this.$message.success(res.meta.msg);
          } else {
            this.$message.error(res.meta.msg);
            userinfo.mg_state = !userinfo.mg_state;
          }
        });
    },
    // 分页的每一页的数据个数
    handleSizeChange(newsize) {
      this.puerylist.pagesize = newsize;
      this.getuserlist();
    },
    // 页码数
    handleCurrentChange(newpage) {
      this.puerylist.pagenum = newpage;
      this.getuserlist();
    },
    // 关闭添加用户事刷新其中的内容
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 提交
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          const res = await this.$http.post(uri.postusers, this.addtian);
          console.log(res);
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg);
            this.addDialogVisible = false;
          } else {
            this.$message.error("添加失败")
          }
        }
      });
    },
    // 修改用户，根据id获取对应的数据
    xiugai(id) {
      this.$http.get(uri.getuserid + "/" + id).then((res) => {
        // console.log(res);
        if (res.meta.status === 200) {
          this.editForm = res.data;
          this.editdialogVisible = true;
        } else {
          this.$message.error(res.meta.msg);
        }
      });
    },
    // 修改用户关闭刷新其中内容
    editDialogClosed(){
      this.$refs.editFormref.resetFields()
    },
    // 修改用户的提交
    editFormadd(){
      this.$refs.editFormref.validate(async valid=>{
        if(valid){
          const res = await this.$http.put(uri.putuserid+"/"+this.editForm.id,{
            email:this.editForm.email,
            mobile:this.editForm.mobile
          })
          // console.log(res)
          if(res.meta.status===200){
            this.$message.success(res.meta.msg)
            this.editdialogVisible=false
          }else{
            this.$message.error("修改用户失败")
          }
        }
      })
    },
    // 删除
   async open(id){
     const confirmResult=await this.$confirm('永久删除该用户，是否继续？','提示',{
        confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
     }).catch((err)=>err)
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
     if(confirmResult!=='confirm'){
       return this.$message.info("已取消删除")
     }else{
       const res= await this.$http.delete(uri.deleteusers+"/"+id)
       if(res.meta.status===200){
         this.$message.success(res.meta.msg)
        this.getuserlist();
       }else{
         this.$message.error("删除用户失败")
       }
     }
    },
    // 分配角色的按钮
    async setRole(nodek){
      // console.log(nodek)
      this.userinfo=nodek
      // 在展示对话框之前，获取所有角色的列表
    const res=await this.$http.get(uri.getroles)
    console.log(res)
    if(res.meta.status===200){
      this.roleslist=res.data
    }else{
      this.$message.error(res.meta.msg)
    }
      this.setRoledialogVisible=true
    },
    // 分配角色的提交
   async saveRoleinfo(){
      if(!this.selectedRoleid){
        this.$message.error("请选择要分配的角色")
      }else{
        const res=await this.$http.put(uri.putuserrole+"/"+this.userinfo.id+"/role",{rid:this.selectedRoleid})
        console.log(res)
        if(res.meta.status===200){
          this.$message.success(res.meta.msg)
          this.setRoledialogVisible=false
          this.getuserlist()
        }else{
          this.$message.error(res.meta.msg)
        }
      }
    },
    // 关闭对话框刷新其中的数据
    setRoleDialogClosed(){
      this.selectedRoleid=""
      this.userinfo={}
    }
  },
};
</script>

<style lang="less" scoped>
.el-row {
  margin-bottom: 20px;
}
</style>
